
 <!DOCTYPE HTML>
<html lang="ch">
<head>
  <meta charset="UTF-8">
  
    <title>斐波那契数列 | Yuan</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="Luo Yuan">
    

    
    <meta name="description" content="斐波那契数列是有一个传奇的数学家基于一对非常能生的兔子提出的（喜欢数学游戏的卖兔子的商人？）：一对兔子每个月能生出一对小兔子来。如果所有兔都不死，那么一年以后可以繁殖多少对兔子？每个月兔子数量最终构成了一个了一个神奇的数列，这数列中除了第零项和第一项，其他所有的项都等于前面两项之和：F(n) &#x3D; F(n-1) + F(n-2)">
<meta property="og:type" content="article">
<meta property="og:title" content="斐波那契数列">
<meta property="og:url" content="http://luoyuan800.github.io/2017/01/03/fib-java/index.html">
<meta property="og:site_name" content="Yuan">
<meta property="og:description" content="斐波那契数列是有一个传奇的数学家基于一对非常能生的兔子提出的（喜欢数学游戏的卖兔子的商人？）：一对兔子每个月能生出一对小兔子来。如果所有兔都不死，那么一年以后可以繁殖多少对兔子？每个月兔子数量最终构成了一个了一个神奇的数列，这数列中除了第零项和第一项，其他所有的项都等于前面两项之和：F(n) &#x3D; F(n-1) + F(n-2)">
<meta property="og:locale">
<meta property="article:published_time" content="2017-01-03T08:19:43.000Z">
<meta property="article:modified_time" content="2021-04-22T08:03:37.214Z">
<meta property="article:author" content="Luo Yuan">
<meta name="twitter:card" content="summary">

    
    <link rel="alternative" href="/atom.xml" title="Yuan" type="application/atom+xml">
    
    
    <link rel="icon" href="/img/favicon.ico">
    
    
    <link rel="apple-touch-icon" href="/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/jacman.jpg">
    
    
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/%02.css">
<link rel="stylesheet" href="/.css">

<meta name="generator" content="Hexo 5.4.0"></head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/"><img src="/img/logo.png" alt="Yuan" title="Yuan"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/" title="Yuan">Yuan</a></h1>
				<h2 class="blog-motto">一点一滴，积累技术</h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/">Home</a></li>
					
						<li><a href="/archives">Archives</a></li>
					
						<li><a href="/about">About</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:luoyuan800.github.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/2017/01/03/fib-java/" title="斐波那契数列" itemprop="url">斐波那契数列</a>
  </h1>
  <p class="article-author">By
       
		<a href="/about" title="Luo Yuan" target="_blank" itemprop="author">Luo Yuan</a>
		
  <p class="article-time">
    <time datetime="2017-01-03T08:19:43.000Z" itemprop="datePublished"> Published 2017-01-03</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			
		
		</div>
		
		<p>斐波那契数列是有一个传奇的数学家基于一对非常能生的兔子提出的（喜欢数学游戏的卖兔子的商人？）：一对兔子每个月能生出一对小兔子来。如果所有兔都不死，那么一年以后可以繁殖多少对兔子？每个月兔子数量最终构成了一个了一个神奇的数列，这数列中除了第零项和第一项，其他所有的项都等于前面两项之和：<code>F(n) = F(n-1) + F(n-2)</code></p>
<span id="more"></span>

<p>这里我先不讨论斐波拉契数列的各种事神奇的特性，比如它和黄金分割的关系，比如自然界的花瓣或者树叶或者数字与斐波拉契数列的巧合，比如晶体原子排列和斐波拉契数列的关联，比如研究股票的某些坑神尝试使用斐波拉契数列去探索跌涨规律等等。总之，看到斐波拉契数列你就会怀疑我们的世界是不是就是某个更高级的文明根据一堆奇奇怪怪数学原理来设计的呢……<br>在这里我就简单研究下怎么使用java实现计算斐波拉契数列的第N个数。<br>首先斐波拉契数列的特性就是一种递归的实现，所以我们可以简单的使用递归的方式求解它。代码结构优雅简洁：</p>
<pre><code>int calculateRecursion(int n)&#123;
        if(n &lt; 2)&#123;
            return n;
        &#125;
        return calculateRecursion(n -1) + calculateRecursion(n -2);
&#125;
</code></pre>
<p>但是递归算法终究是会导致资源的浪费和堆栈占用的暴增，但计算数值一旦变大，最终会导致堆栈溢出。并且这个递归算法中对同样的位数的斐波那契数进行了重复计算和存储也导致了计算资源的浪费。<br>代码结构简洁并不一定代码代码效率好，那么我们尝试把递归计算过程的数字保存下来，当发现已经计算过的就直接使用：</p>
<pre><code>Integer[] fibs = new Integer[n+1];
int calculateRecursion(int n)&#123;
    if(fib[n] == null &amp;&amp; n &lt; 2)&#123;
        fibs[n] = n;
    &#125;else if(fib[n] == null)&#123;
        fibs[n] = calculateRecursion(n -1) + calculateRecursion(n -2);
    &#125;
    return fibs[n];
&#125;
</code></pre>
<p>这样我们递归终于可以省掉一些额外的计算消耗了，但是代码好像看起来越来越臃肿了。那么我们尝试下不使用递归来实现另外一种求解斐波拉契数列的方式。</p>
<pre><code>int calculateLinear(int n)&#123;
    if(n &lt; 2)&#123;
        return n;
    &#125;
    int f = new int[n + 1];
    f[0] = 0; f[1] = 1;
    for(int i = 2; i&lt; n; i++)&#123;
        f[i]= f[i-1] + f[i-2];
    &#125;
    return f[n];
&#125;
</code></pre>
<p>这个段代码我们还可以继续简化它的存储占用。因为斐波拉契数列第N个数只和它的前两个相邻数相关，所以在计算过程中，其实我们只需要存储相关两个数，就可以计算出第N个数了，完全没有必要存储每一位的数值。</p>
<pre><code>int calculateLinear(int n)&#123;
    //看，我们连数值界限判断都可以省掉了，真是太优雅了！
    int f0 = 0, f1 = 1;
    for(int i = 0; i&lt; n; i++)&#123;
        f1 = f1 + f0;
        f0 = f1 - f0;
    &#125;
    return f0;
&#125;
</code></pre>
<p>嗯，这段代码实现也很简洁，并且成功的减少了内存堆栈的消耗。Good！<br>那么下一个问题来了，斐波拉契数列值是指数增长的，但是java中int类型的最大值是</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">2^&#123;31&#125; -1 &#x3D; 2147483647</span><br></pre></td></tr></table></figure>
<p>当使用上面实现的代码计算就可以发现计算到F[47]的时候就出现溢出了……那么我们换成long类型呢？</p>
<pre><code>long calculateLinear(long n)&#123;
    
    long f0 = 0, f1 = 1;
    for(long i = 0; i&lt; n; i++)&#123;
        f1 = f1 + f0;
        f0 = f1 - f0;
    &#125;
    return f0;
&#125;
</code></pre>
<p>结果是只能计算到前92个……那只好用上BigInteger了：</p>
<pre><code>BigInteger calculateLinear(BigInteger n)&#123;
    BigInteger big1 = new BigInteger(&quot;1&quot;);
    BigInteger f0 = new BigInteger(&quot;0&quot;), f1 = big1;
    for(BigInteger i = new BigInteger(&quot;0&quot;); i.compareTo(n) == -1; i = i.add(big1))&#123;
        f1 = f1.add(f0);
        f0 = f1.subtract(f0);
    &#125;
    return f0;
&#125;
</code></pre>
<p>这样我们就可以计算任意大小的斐波拉契数列的数值了么？<br>至少我跑了一晚上，计算到了182324，都没有出现什么错误，只不过是越到后面，计算消耗的时间越长就是了……</p>
<pre><code>    fib(182324):    1297286608306366788170744137779958588200611866878942632507224818788883057962361182304458754935156188970882290447672
    ……
</code></pre>
  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/categories/%E7%BC%96%E7%A8%8B-Java/">编程-Java</a>
</div>


</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://luoyuan800.github.io/2017/01/03/fib-java/" data-title="斐波那契数列 | Yuan" data-tsina="" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/2017/01/03/coin-java/" title="假币问题">
  <strong>上一篇：</strong><br/>
  <span>
  假币问题</span>
</a>
</div>


<div class="next">
<a href="/2016/10/30/piped-java/"  title="PipedOutputStream和PipedInputStream">
 <strong>下一篇：</strong><br/> 
 <span>PipedOutputStream和PipedInputStream
</span>
</a>
</div>

</nav>

	



</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/categories/杂物-医学/" title="杂物-医学">杂物-医学<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-Java/" title="编程-Java">编程-Java<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-Linux-Unix/" title="编程-Linux/Unix">编程-Linux/Unix<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-工具/" title="编程-工具">编程-工具<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-网络协议/" title="编程-网络协议">编程-网络协议<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/categories/网站-开发/" title="网站-开发">网站-开发<sup>2</sup></a></li>
		  
		
		</ul>
</div>


  

  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=&verifier=&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m Luo Yuan in Zhuhai. <br/>
			Here is my place for knowledge accumulation.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2021 
		
		<a href="/about" target="_blank" title="Luo Yuan">Luo Yuan</a>
		
		
		</p>
</div>
</footer>
    <script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>
<script src="/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>











<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/img/scrollup.png"/></a>
	</div>
	<script src="/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
